define(['underscore','backbone','jquery','views/widget','text!templates/image.html','elfinder','jquery-ui-1.8.13'], function(_,Backbone,$,ViewWidget,ImageTemplate){
    var ImageView = ViewWidget.extend({
        template : _.template(ImageTemplate),
        events : {
            'click .actions .save' : 'save',
            'click .actions .cancel' : 'cancel',
            'click .widget-form a' : 'changeImage'
        },
        initialize : function(){
            this.model.bind('change', this.render, this);
            this.model.view = this;
        },
        edit : function(event){
            ViewWidget.prototype.edit.call(this);
            return false;
        },
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            
            return this;
        },
        changeImage : function(){
            if($("#finder-"+this.model.get('id')).length == 0) {
                $("body").append($("<div/>").attr("id", "finder-"+this.model.get('id')));
                var f = $('#finder-'+this.model.get('id')).elfinder({
                    url : $('.connection_url').attr('href'),
                    lang : 'en',
                    dialog : { width : 900, modal : true, title : "File manager", zIndex: 7777777 },
                    editorCallback : $.proxy(function(src) {
                        this.$('.widget-form a img').attr('src', src);
                    },this),
                    closeOnEditorCallback: true
                });
            } else {
                $("#finder-"+this.model.get('id')).elfinder("open");
            }
        },
        save : function()
        {
            Backbone.emulateJSON = true;
            var exported = this.$('.export input:checkbox').attr('checked') ? 1 : 0;
            this.model.save({content:this.$('.widget-form a img').attr('src'),exported : exported});
            this.cancel();
            return false;
        }
    });
    return ImageView;
});